﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WWWSiteHelper
{
    public class HTMLUtilities
    {
        public class Localizator
        {
            public Localizator(int begin, int length)
            {
                this.Begin = begin;
                this.Length = length;
            }

            public int Begin { get; private set; }
            public int Length { get; private set; }
        }

        public static TagAttributeValueKnowledge.FilledTag getFirstTagAttributes(string full)
        {
            try
            {
                TagAttributeValueKnowledge knowledge = TagAttributeValueKnowledge.parse(full);
                IList<TagAttributeValueKnowledge.FilledTag> tags = knowledge.getAll();
                if (tags.Count == 0)
                {
                    return new TagAttributeValueKnowledge.FilledTag(null, null);
                }
                else
                {
                    return tags.First();
                }
            }
            catch (ParseException)
            {
                return new TagAttributeValueKnowledge.FilledTag(null, null);
            }
        }

        public static Localizator LocalizeTag(String text, int idx, int radius)
        {
            int threshold = Math.Max(0, idx - radius);
            for (int j = idx - 1; j >= threshold; --j)
            {
                switch (text[j])
                {
                    case '<':
                        int index = text.IndexOf('>', j, Math.Min(radius, text.Length - j));
                        index = (index == -1 ? 0 : index + 1 - j);
                        return new Localizator(j, index);
                    case '>':
                        return null;
                }
            }
            return null;
        }
    }
}
